package top.yuechenc.manage.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.yuechenc.manage.common.token.ShopResult;
import top.yuechenc.manage.common.token.TokenService;
import top.yuechenc.manage.common.token.UserLoginToken;
import top.yuechenc.manage.common.utils.DataUtil;
import top.yuechenc.manage.entity.SpManager;
import top.yuechenc.manage.entity.SpManagerDto;
import top.yuechenc.manage.entity.SpRole;
import top.yuechenc.manage.service.ManagerService;
import top.yuechenc.manage.service.RoleService;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 用户操作接口
 *
 * @author Zhiwei Wang
 * @date 2020/2/17 20:01
 */
@Api(description = "用户操作接口")
@RestController
@RequestMapping(value = "/api")
public class ManagerController {
    private static final Logger log= LoggerFactory.getLogger(ManagerController.class);

    @Autowired
    private ManagerService managerService;
    @Autowired
    TokenService tokenService;
    @Autowired
    private RoleService roleService;

    /**
     * 管理员登录
     */
    @ApiOperation(value = "登录系统")
    @PostMapping("/mg_login")
    private ShopResult login(@RequestBody @ApiParam(name = "管理员对象", value = "传入json格式", required = true) SpManager manager) {
        ShopResult result;
        if (manager != null && manager.getMgName() != null && !"".equals(manager.getMgName())) {
            try {
                SpManagerDto spManager = managerService.getManagerByUsername(manager.getMgName());
                if (spManager == null) {
                    result = new ShopResult(205, "用户不存在！");
                } else {
                    if (spManager.getMgPwd().equals(manager.getMgPwd())) {
                        String token = tokenService.getToken(spManager);
                        spManager.setToken(token);
                        log.info("管理员登录，用户名={}",manager.getMgName());
                        result = new ShopResult(ShopResult.Metaa.OK, spManager);
                    } else {
                        result = new ShopResult(416, "密码错误！");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.debug(e.toString());
                result=new ShopResult(ShopResult.Metaa.INTERNAL_SERVER_ERROR,e);
            }
        } else {
            result = new ShopResult(415, "请输入用户名！");
        }
        return result;
    }

    /**
     * 条件分页获取管理员列表
     */
    @ApiOperation(value = "条件分页获取管理员列表")
    @UserLoginToken
    @PostMapping("/manager/getByParam")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "query", defaultValue = "10")
    })
    private ShopResult findAll(@RequestBody @ApiParam(name = "管理员对象", value = "传入json格式") SpManagerDto manager, int pageNum, int pageSize) {
        PageInfo pageInfo = null;
        ShopResult result=null;
        try {
            pageInfo = managerService.findListByParam(manager, pageNum, pageSize);
            List<SpManager> spManagerList = pageInfo.getList();
            List<SpManagerDto> spManagerDtoList = handleSpManagerOV(spManagerList);
            for (int i = 0; i < spManagerDtoList.size(); i++) {
                String roleId = spManagerDtoList.get(i).getRoleId();
                SpRole spRole = roleService.findRoleById(roleId);
                if(spRole!=null) {
                    spManagerDtoList.get(i).setRoleName(spRole.getRoleName());
                }else {
                    spManagerDtoList.get(i).setRoleName("无角色");
                }
            }
            pageInfo.setList(spManagerDtoList);
            log.info("分页获取管理员列表，managerPageInfo={}",pageInfo);
            result=new ShopResult(ShopResult.Metaa.OK, pageInfo);
        } catch (Exception e) {
            log.debug(e.toString());
            e.printStackTrace();
        }
        return result;
    }

    private List<SpManagerDto> handleSpManagerOV(List<SpManager> spManagerList) {
        List<SpManagerDto> spManagerDtos = new ArrayList<>();
        for (int i = 0; i < spManagerList.size(); i++) {
            SpManagerDto spManagerDto = new SpManagerDto();
            spManagerDto.setRoleId(spManagerList.get(i).getRoleId());
            spManagerDto.setMgId(spManagerList.get(i).getRoleId());
            spManagerDto.setMgState(spManagerList.get(i).getMgState());
            spManagerDto.setMgTime(spManagerList.get(i).getMgTime());
            spManagerDto.setMgEmail(spManagerList.get(i).getMgEmail());
            spManagerDto.setMgMobile(spManagerList.get(i).getMgMobile());
            spManagerDto.setMgName(spManagerList.get(i).getMgName());
            spManagerDto.setMgPwd(spManagerList.get(i).getMgPwd());

            spManagerDtos.add(spManagerDto);
        }
        return spManagerDtos;
    }

    @ApiOperation(value = "添加管理员")
    @UserLoginToken
    @PostMapping("/manager/add")
    private ShopResult addManager(@RequestBody @ApiParam(name = "管理员对象", value = "传入json格式") SpManager spManager) {
        ShopResult result;
        if (spManager != null) {
            spManager.setMgId(UUID.randomUUID().toString());
            spManager.setMgTime(DataUtil.getStringDate());
            try {
                managerService.addManager(spManager);
                log.info("添加管理员,manager={}",spManager);
                result = new ShopResult(ShopResult.Metaa.OK, spManager);
            } catch (Exception e) {
                e.printStackTrace();
                log.debug(e.toString());
                result = new ShopResult(ShopResult.Metaa.CREATED_FAIL, e.getMessage());
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.CREATED_FAIL, "创建失败：管理员信息不能为空！");
        }
        return result;
    }

    @ApiOperation(value = "修改管理员状态")
    @UserLoginToken
    @PutMapping("manager/state")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mgId", value = "管理员编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "mgState", value = "管理员状态", dataType = "int", paramType = "query", defaultValue = "0")
    })
    private ShopResult updateState(String mgId, Integer mgState) {
        ShopResult result;
        if (mgId != null && !"".equals(mgId)) {
            if (mgState != null) {
                SpManager manager = new SpManager();
                manager.setMgId(mgId);
                try {
                    manager = managerService.findManagerById(mgId);
                    manager.setMgState(mgState);
                    managerService.updateState(manager);
                    log.info("修改管理员状态,manager={}",manager);
                    result = new ShopResult(ShopResult.Metaa.UPDATE, manager);
                } catch (Exception e) {
                    log.debug(e.toString());
                    result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, e);
                }
            } else {
                result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "请输入管理员状态！");
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "请输入管理员编号！");
        }
        return result;
    }

    @ApiOperation(value = "根据id查询管理员信息")
    @UserLoginToken
    @GetMapping("manager/getById")
    @ApiImplicitParam(name = "mgId", value = "管理员编号", dataType = "string", paramType = "query", required = true)
    private ShopResult getById(String mgId) {
        ShopResult result;
        if (mgId != null && !"".equals(mgId)) {
            try {
                SpManager spManager = managerService.findManagerById(mgId);
                if (spManager != null) {
                    log.info("根据id查询管理员信息,manager={}",spManager);
                    result = new ShopResult(ShopResult.Metaa.SELECT, spManager);
                } else {
                    result = new ShopResult(ShopResult.Metaa.SELECT, "未查到该编号对应的管理员");
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.debug(e.toString());
                result = new ShopResult(ShopResult.Metaa.SELECT_FAIL, e);
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.SELECT_FAIL, "请输入管理员编号！");
        }
        return result;
    }

    @ApiOperation(value = "根据id修改管理员信息")
    @UserLoginToken
    @PutMapping("manager/updById")
    private ShopResult updById(@RequestBody @ApiParam(name = "管理员对象", value = "传入json格式") SpManager manager) {
        ShopResult res;
        if (manager.getMgId() != null && !"".equals(manager.getMgId())) {
            try {
                managerService.updById(manager);
                manager = managerService.findManagerById(manager.getMgId());
                log.info("根据id修改管理员信息,manager={}",manager);
                res = new ShopResult(ShopResult.Metaa.UPDATE, manager);
            } catch (Exception e) {
                log.debug(e.toString());
                res = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, e.getMessage());
            }
        } else {
            res = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "：请输入管理员编号！");
        }
        return res;
    }

    @ApiOperation(value = "根据id删除管理员信息")
    @UserLoginToken
    @DeleteMapping("manager/delById")
    @ApiImplicitParam(name = "mgId", value = "管理员编号", dataType = "string", paramType = "query", required = true)
    private ShopResult delById(String mgId) {
        ShopResult res;
        if (mgId != null && !"".equals(mgId)) {
            try {
                managerService.delById(mgId);
                log.info("根据id删除管理员信息,mgId={}",mgId);
                res = new ShopResult(ShopResult.Metaa.DELETED);
            } catch (Exception e) {
                log.debug(e.toString());
                res = new ShopResult(ShopResult.Metaa.DELETED_FAIL, e.getMessage());
            }
        } else {
            res = new ShopResult(ShopResult.Metaa.DELETED_FAIL, "：请输入管理员编号！");
        }
        return res;
    }

    @ApiOperation(value = "修改用户角色")
    @UserLoginToken
    @PutMapping("manager/updRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mgId", value = "管理员编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "roleId", value = "管理员角色编号", dataType = "int", paramType = "query")
    })
    private ShopResult updRole(String mgId, String roleId) {
        ShopResult result;
        if (mgId != null && !"".equals(mgId)) {
            if (roleId != null && !"".equals(roleId)) {
                SpManager manager = new SpManager();
                manager.setMgId(mgId);
                try {
                    manager = managerService.findManagerById(mgId);
                    manager.setRoleId(roleId);
                    managerService.updateState(manager);
                    log.info("修改用户角色,manager={}",manager);
                    result = new ShopResult(ShopResult.Metaa.UPDATE, manager);
                } catch (Exception e) {
                    log.debug(e.toString());
                    result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, e.getMessage());
                }
            } else {
                result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "请输入角色编号！");
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "请输入管理员编号！");
        }
        return result;
    }
}
